package com.ids.transfer.task;

import java.util.Date;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import com.ids.transfer.config.TaskConfig;
import com.ids.transfer.controler.ExtraTask;
import com.ids.transfer.data.XmlParse;
import com.ids.transfer.job.AutoTransferJob;
import com.ids.transfer.util.StrCharUtil;

public class QuartzTask {

	private final Log logger = LogFactory.getLog(getClass());

	public void initJobs() {
		
		HashMap<String, String> taskMap=null;
		try {
			taskMap = XmlParse.getAllTaskId();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		//---------------------
		
		int num = 0;
		for (String taskid : taskMap.keySet()) {
			try {
				TaskConfig tc = new TaskConfig(taskid);
				Date startTime = null;
				Date endTime = null;
				String cronExpression = null;

				if (!StrCharUtil.isNull(tc.getStarttime())) {
					startTime = tc.getStarttime();
				} else {
					startTime = new Date(System.currentTimeMillis() + 1000l);
				}
				if (!StrCharUtil.isNull(tc.getEndtime())) {
					endTime = tc.getEndtime();
				}
				if (StrCharUtil.isNull(tc.getCronexpression())) {
					throw new IllegalArgumentException("XML里CronExpression不能为空");
				}
				cronExpression = tc.getCronexpression();

				++num;
				Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
				System.out.println("initJobs");
				logger.warn("初始化任务:" + taskid + "开始时间:" + startTime + "结束时间:"
						+ endTime);
				// 创建trigger//有endTime可以清除任务
				Trigger trigger = new CronTrigger("trigger",
						Scheduler.DEFAULT_GROUP + num, "job" + num,
						Scheduler.DEFAULT_GROUP + num, startTime, endTime,
						cronExpression);

				// 安排任务
				JobDetail job = new JobDetail("job" + num,
						Scheduler.DEFAULT_GROUP + num, AutoTransferJob.class);

				// quartz注入
				// 在这里控制
				ExtraTask at = new ExtraTask(taskid);
				JobDataMap map = new JobDataMap();
				map.put("at", at);
				job.setJobDataMap(map);
				scheduler.scheduleJob(job, trigger);
				scheduler.start();
				logger.warn("初始化任务完毕");
			} catch (Exception e) {
				logger.error("初始化任务失败:" + taskid);
				throw new RuntimeException("初始化任务失败", e);
			}
		}//end for
	}

	public static void main(String[] args) {
		new QuartzTask().initJobs();
	}
}
